package com.hancher.common.javautil;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.List;

/**
 * 描述 : gson 工具 <br/>
 * 时间 : 2023/11/18 10:54 <br/>
 * 作者 : Hancher ytu_shaoweijie@163.com
 */
public class GsonUtil {
    public static HashMap<String, Object> obj2Map(Object o) {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<>();
        String gsonStr = gson.toJson(o);
        map = gson.fromJson(gsonStr, map.getClass());
        return map;
    }

    public static HashMap<String, Object> str2Map(String o) {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<>();
        map = gson.fromJson(o, map.getClass());
        return map;
    }

    public static String obj2JsonStr(Object o) {
        if (o == null) {
            return "null";
        }
        Gson gson = new Gson();
        return gson.toJson(o);
    }

    public static <T> T str2Obj(String s, T data) {
        Gson gson = new Gson();
        data = (T) gson.fromJson(s, data.getClass());
        return data;
    }

    public static <T> List<T> str2ObjList(String s) {
        Gson gson = new Gson();
        List<T> list = gson.fromJson(s, new TypeToken<List<T>>() {
        }.getType());
        return list;
    }

    public static <T> T str2Obj2(String s, Class<T> cls) {
        Gson gson = new Gson();
        T data = gson.fromJson(s, cls);
        return data;
    }

    public static <T> List<T> cloneObj(List<T> rvList) {
        String str = obj2JsonStr(rvList);
        return str2ObjList(str);
    }

    public static <T> T copy(Object obj, Class<T> beanClazz) {
        String str = obj2JsonStr(obj);
        return str2Obj2(str, beanClazz);
    }
}
